package com.example.activitydemo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class Activity5 : AppCompatActivity() {
    private lateinit var timeTv: TextView
    private lateinit var startBtn: Button
    private lateinit var pauseBtn: Button
    private lateinit var resetBtn: Button

    private var baseTime: Long = 0L
    private var elapsedTime: Long = 0L
    private var isRunning = false
    private val handler = Handler(Looper.getMainLooper())
    private val timerTask = object : Runnable {
        override fun run() {
            if (isRunning) {
                val currentTime = System.currentTimeMillis() - baseTime + elapsedTime
                updateTimeDisplay(currentTime)
                handler.postDelayed(this, 100)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 关键修改：将 activity5 改为 activity_5
        setContentView(R.layout.activity_5)

        timeTv = findViewById(R.id.time_tv)
        startBtn = findViewById(R.id.start_btn)
        pauseBtn = findViewById(R.id.pause_btn)
        resetBtn = findViewById(R.id.reset_btn)

        if (savedInstanceState != null) {
            elapsedTime = savedInstanceState.getLong("elapsedTime")
            isRunning = savedInstanceState.getBoolean("isRunning")
            baseTime = savedInstanceState.getLong("baseTime")
            updateTimeDisplay(elapsedTime)
            if (isRunning) {
                handler.post(timerTask)
            }
        }

        startBtn.setOnClickListener {
            if (!isRunning) {
                baseTime = System.currentTimeMillis()
                isRunning = true
                handler.post(timerTask)
            }
        }

        pauseBtn.setOnClickListener {
            if (isRunning) {
                elapsedTime += System.currentTimeMillis() - baseTime
                isRunning = false
                handler.removeCallbacks(timerTask)
            }
        }

        resetBtn.setOnClickListener {
            isRunning = false
            handler.removeCallbacks(timerTask)
            elapsedTime = 0L
            updateTimeDisplay(0L)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putLong("elapsedTime", elapsedTime)
        outState.putBoolean("isRunning", isRunning)
        outState.putLong("baseTime", baseTime)
    }

    private fun updateTimeDisplay(milliseconds: Long) {
        val minutes = (milliseconds / 1000) / 60
        val seconds = (milliseconds / 1000) % 60
        val mills = milliseconds % 1000
        timeTv.text = String.format("%02d:%02d.%03d", minutes, seconds, mills)
    }
}